package logic

import (
	"Bluebell/common/jwt"
	"Bluebell/common/snowflake"
	"Bluebell/dao/mysql"
	"Bluebell/models"
	"errors"
	"golang.org/x/crypto/bcrypt"
)

func Register(p *models.ParamsSignUp) (err error) {
	//判断用户是否存在
	if mysql.IsUserExist(p.UserName) {
		return errors.New("用户已存在")
	}
	//生成UID
	userID, err := snowflake.GetID()
	user := &models.User{
		UserID:   userID,
		UserName: p.UserName,
		Password: p.Password,
	}
	//保存入数据库
	return mysql.CreateUser(user)
	//存入redis缓存
}

func Login(p *models.ParamsLogin) (user *models.User, err error) {
	user, err = mysql.GetUserByUsername(p.UserName)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(p.Password)); err != nil {
		return nil, errors.New("密码错误")
	}
	//token发放
	_, token, err := jwt.GenToken(user.UserID)
	user.Token = token
	//返回結果
	return user, nil
}
